package com.hk.core.data.jpa.repository.advice;

import com.hk.commons.util.Lazy;
import com.hk.commons.util.SpringContextHolder;
import lombok.RequiredArgsConstructor;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.util.Optional;

/**
 * @author Kevin
 * @date 2024-07-03 17:51
 */
@RequiredArgsConstructor
public class RepositoryInterfaceAdvice implements MethodInterceptor {

    private final Class<?> repositoryInterface;

    private final Lazy<Optional<RepositoryInterfaceAround>> repositoryInterfaceAround = Lazy.of(() ->
            SpringContextHolder.getBeanIfExist(RepositoryInterfaceAround.class));

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Optional<RepositoryInterfaceAround> interfaceAround = repositoryInterfaceAround.get();
        if (interfaceAround.isPresent()) {
            RepositoryInterfaceAround around = interfaceAround.get();
            try {
                around.before(invocation, repositoryInterface);
                return invocation.proceed();
            } finally {
                around.after(repositoryInterface);
            }
        }
        return invocation.proceed();
    }
}
